package demo2;

import java.util.Stack;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: asus
 * Date: 2024-12-11
 * Time: 22:01
 */

/**
 * 给出一个仅包含字符'(',')','{','}','['和']',的字符串，判断给出的字符串是否是合法的括号序列
 * 括号必须以正确的顺序关闭，"()"和"()[]{}"都是合法的括号序列，但"(]"和"([)]"不合法。
 */
public class Main {
    public boolean isValid (String s) {
        Stack<Character> stack = new Stack<>();
        for (char c :
                s.toCharArray()) {
            if (c == '(' || c == '{' || c == '[') {
                stack.push(c);
            } else {
                if (stack.isEmpty()) {
                    return false;
                }
                char t = stack.peek();
                if (c == ')' && t == '(' ||
                        c == ']' && t == '[' ||
                        c == '}' && t == '{') {
                    stack.pop();
                } else {
                    return false;
                }
            }
        }
        return stack.isEmpty();
    }
}
